package com.ruoyi.bizsys.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.Map;

import com.ruoyi.bizsys.domain.ProductDeferredInfo;
import com.ruoyi.bizsys.domain.ProductInfoVo;
import com.ruoyi.bizsys.domain.ProductRelationDeferred;
import com.ruoyi.bizsys.mapper.ProductDeferredInfoMapper;
import com.ruoyi.bizsys.mapper.ProductRelationDeferredMapper;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.bizsys.mapper.ProductInfoMapper;
import com.ruoyi.bizsys.domain.ProductInfo;
import com.ruoyi.bizsys.service.IProductInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


/**
 * 产品信息Service业务层处理
 *
 * @author african-loan
 * @date 2021-12-30
 */
@Service
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoMapper, ProductInfo> implements IProductInfoService {

    @Autowired
    private ProductDeferredInfoMapper productDeferredInfoMapper;

    @Autowired
    private ProductRelationDeferredMapper productRelationDeferredMapper;


    /**
     * 查询产品信息
     *
     * @param productId 产品信息ID
     * @return 产品信息
     */
    @Override
    public ProductInfoVo selectProductInfoById(Long productId) {
        ProductInfo productInfo = this.getById(productId);
        ProductInfoVo productInfoVo = new ProductInfoVo();
        BeanUtils.copyProperties(productInfo, productInfoVo);
        List<ProductRelationDeferred> productRelationDeferreds = productRelationDeferredMapper.selectCodeById(productId);
        String defeered = "";
        for (ProductRelationDeferred productRelationDeferred : productRelationDeferreds) {
            defeered = defeered + productRelationDeferred.getProductDeferredId() + ",";
        }
        productInfoVo.setDeferredId(defeered);
        return productInfoVo;
    }

    /**
     * 查询产品信息列表
     *
     * @param productInfo 产品信息
     * @return 产品信息
     */
    @Override
    public List<ProductInfo> selectProductInfoList(ProductInfo productInfo) {
        return this.list(new QueryWrapper<>(productInfo).last("order by id desc"));
    }

    /**
     * 新增产品信息
     *
     * @param productInfo 产品信息
     * @return 结果
     */
    @Override
    public int insertProductInfo(ProductInfo productInfo) {
        ProductInfo productInfoQ = new ProductInfo();
        productInfoQ.setProductType(productInfo.getProductType());
        // 用户等级
        productInfoQ.setCreditRating(productInfo.getCreditRating());

        productInfoQ.setPeriodNum(productInfo.getPeriodNum());
        List<ProductInfo> productInfos = this.selectProductInfoList(productInfoQ);
        if (productInfos.size() > 0) {
            throw new BusinessException(RspEnmu.DATA_ALREADY_EXISTS);
        }
        productInfo.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(productInfo);
    }

    /**
     * 修改产品信息
     *
     * @param productInfoVo 产品信息
     * @return 结果
     */
    @Override
    public int updateProductInfo(ProductInfoVo productInfoVo) {
        Long product_code = this.getOne(new QueryWrapper<ProductInfo>().eq("product_code", productInfoVo.getProductCode())).getId();
        if (!StringUtils.isEmpty(productInfoVo.getDeferredId())) {
            productInfoVo.setTags("-2");
            List<String> deferredId = Arrays.asList(productInfoVo.getDeferredId().split(","));
            for (String integer : deferredId) {
                ProductRelationDeferred productRelationDeferred = new ProductRelationDeferred();
                productRelationDeferred.setProductId(product_code);
                productRelationDeferred.setProductDeferredId(Integer.valueOf(integer));
                productRelationDeferred.setState("1");
                productRelationDeferred.setStatus(1);
                productRelationDeferred.setCreateTime(new Date());
                productRelationDeferred.setUpdateTime(new Date());
                productRelationDeferredMapper.insert(productRelationDeferred);
            }
        }
        return baseMapper.updateById(productInfoVo);
    }

    /**
     * 批量删除产品信息
     *
     * @param ids 需要删除的产品信息ID
     * @return 结果
     */
    @Override
    public int deleteProductInfoByIds(Long[] ids) {
        List<ProductInfo> list = list(new QueryWrapper<ProductInfo>().in("id", ids));
        list.forEach(e -> {
            if ("Y".equals(e.getDefult())) {
                throw new BusinessException("默认产品不可删除！");
            }
        });
        productRelationDeferredMapper.updateByIds(ids);
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除产品信息信息
     *
     * @param id 产品信息ID
     * @return 结果
     */
    @Override
    public int deleteProductInfoById(Long id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public ProductInfo getOneByProductCode(String productCode) {
        return getOne(new QueryWrapper<ProductInfo>().eq("product_code", productCode).eq("state", "0"));
    }

    /**
     * 新增页面查询下拉列表
     *
     * @return
     */
    @Override
    public List<ProductDeferredInfo> getFinancial() {
        return productDeferredInfoMapper.selectCode();
    }

    /**
     * 新增产品
     *
     * @param productInfoVo
     * @return
     */
    @Override
    public int saveProductInfo(ProductInfoVo productInfoVo) {
        ProductInfo productInfo = new ProductInfo();
        productInfo.setPeriodNum(productInfoVo.getPeriodNum());
        productInfo.setCreditRating(productInfoVo.getCreditRating());
        productInfo.setState("0");
        List<ProductInfo> productInfos = this.selectProductInfoList(productInfo);
        if (productInfos.size() > 0) {
            throw new BusinessException(RspEnmu.DATA_ALREADY_EXISTS);
        }
        return this.insert(productInfo, productInfoVo);
    }


    /**
     * 保存product_info和product_relation_deferred
     *
     * @param productInfo
     * @param productInfoVo
     * @return
     */
    @Transactional
    public int insert(ProductInfo productInfo, ProductInfoVo productInfoVo) {
        BeanUtils.copyProperties(productInfoVo, productInfo);
        productInfo.setState("0");

        //利率不为0
        if(productInfo.getShowInterestRate().equals(productInfo.getInterestRate())){

        }
        else if (!productInfo.getInterestRate().equals(BigDecimal.ZERO) && productInfo.getShowInterestRate().compareTo(productInfo.getInterestRate()) != 0) {
            //产品展示利率
            BigDecimal showInterestRate = productInfo.getShowInterestRate();
            //产品实际利率
            BigDecimal interestRate = productInfo.getInterestRate();
            //产品金融标签tags
            int show = ((showInterestRate.subtract(interestRate)).divide(showInterestRate, 2, BigDecimal.ROUND_UP)).multiply(BigDecimal.valueOf(100)).intValue();
            productInfo.setTags(show + "%");
        } else if (productInfo.getShowInterestRate().equals(BigDecimal.ZERO) && productInfo.getInterestRate().equals(BigDecimal.ZERO)) {
            productInfo.setTags("-1");
        }
        else if (productInfo.getShowInterestRate().compareTo(productInfo.getInterestRate()) == 0) {

        } else {
            //利率为0
            productInfo.setTags("-1");
        }
        //保存产品
        baseMapper.insert(productInfo);
        //获取产品主键id
        Long id = baseMapper.selectOne(new QueryWrapper<ProductInfo>().eq("product_code", productInfo.getProductCode())).getId();
        //有金融产品
        if (!StringUtils.isEmpty(productInfoVo.getDeferredId())) {
            productInfo.setId(id);
            if (StringUtils.isEmpty(productInfo.getTags())) {
                productInfo.setTags("-2");
            } else {
                productInfo.setTags(productInfo.getTags() + ",-2");
            }
            //更新tags字段
            baseMapper.updateById(productInfo);
            List<String> strings = Arrays.asList(productInfoVo.getDeferredId().split(","));
            for (String string : strings) {
                ProductRelationDeferred productRelationDeferred1 = productRelationDeferredMapper.selectOne(new QueryWrapper<ProductRelationDeferred>().eq("product_id", id).eq("product_deferred_id", string).eq("state", 1));
                if (!StringUtils.isEmpty(productRelationDeferred1)) {
                    throw new BusinessException(RspEnmu.PRODUCT_CODE_EXISTS);
                }
                //金融产品ID
                ProductRelationDeferred productRelationDeferred = new ProductRelationDeferred();
                productRelationDeferred.setProductId(id);
                productRelationDeferred.setProductDeferredId(Integer.valueOf(string));
                productRelationDeferred.setStatus(1);
                productRelationDeferred.setState("1");
                productRelationDeferred.setCreateTime(DateUtils.getNowDate());
                productRelationDeferred.setUpdateTime(DateUtils.getNowDate());
                productRelationDeferredMapper.insert(productRelationDeferred);

            }
        }
        return 1;
    }
}